package android.tusnotas.core;

import android.tusnotas.beans.PushStatus;
import android.tusnotas.connector.webservice.WebServiceCaller;
import android.tusnotas.exception.ProcessingInstancesException;
import android.tusnotas.exception.RemoteReadingException;
import android.tusnotas.parser.subscription.PushSubscriptionParser;
import android.tusnotas.util.Devel;
import android.util.Log;

public class PushUnsubscriptionAnalyser {
	private WebServiceCaller caller = new WebServiceCaller();

	private int ttt = 5;//times to try before giving up connection try
	
	public PushStatus doUnSubscription(String appId, String androidId) throws RemoteReadingException, ProcessingInstancesException{
		String XML = doGetUnSubscription(appId, androidId);
		PushStatus ps = doObtainUnSubscription(XML);
		return ps;
	}

	private PushStatus doObtainUnSubscription(String XML) throws ProcessingInstancesException{
		PushStatus ps = null;
		
		PushSubscriptionParser subscriptionParser = new PushSubscriptionParser();
		try {
			ps = subscriptionParser.parseXML(XML);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ProcessingInstancesException();
		}
		return ps;
	}

	private String doGetUnSubscription(String appId, String androidId) throws RemoteReadingException{
		String XML="";
		try {
			caller.setPushUnsubscription(appId, androidId);
			XML = persistentCaller();
		} catch (Exception e) {
			if( Devel.fullDevel){
				Log.w(this.getClass().getName(), "ERROR WHILE CONNECTING TO WC");
			}
			RemoteReadingException rwce = new RemoteReadingException();
			rwce.setErrorCode(GradeAnalyserStatuses.WEIRD_FAILURE);
			throw rwce;
		}
		return XML;
	}
	
	private String persistentCaller() throws RemoteReadingException{	
		while( ttt > 0){
			try{
				String XML = caller.execute();
				return XML;
			}catch(RemoteReadingException e){}
			ttt--;
		}
		throw new RemoteReadingException();
	}
}
